<?php

class LanguageController extends ERestController {

	/**
	 * @var string the default layout for the views. Defaults to
	 * '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function _filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function _accessRules() {
		return array(
			array('allow',
				'actions'=>array(
					'index',
					'view',
					'create',
					'ajaxUpdateCounter'
				),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('update', 'admin', 'delete'),
				'users'=>array('admin'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->layout = '//layouts/column1';

		$translation = new Translation;

		$this->performTranslationAjaxValidation($translation);

		if (isset($_POST['Translation'])) {
			$translation->attributes = $_POST['Translation'];
			$url = array(
				'translation/create',
				'languageId'=>$id,
				'dialect'=>$translation->dialect,
			);
			$this->redirect($url);
		} else {
			$translation->dialect = 'English';
		}

		$scenario = 'insert';
		if (Yii::app()->user->isGuest) $scenario = 'insertGuest';
		$comment = new Comment($scenario);
		$this->performCommentAjaxValidation($comment);

		if (isset($_POST['Comment'])) {
			$comment->attributes = $_POST['Comment'];
			$comment->languageId = $id;
			if (!Yii::app()->user->isGuest) {
				$comment->userId = Yii::app()->user->id;
			}
			if ($comment->save()) $comment = new Comment;
		}

		$counters = array('viewCount'=>1);
		$condition = 'id = :id';
		$params = array(':id'=>$id);
		Language::model()->updateCounters($counters, $condition, $params);

		$model = $this->loadModel($id);

		$criteria = new CDbCriteria;
		$criteria->order = 'createdAt DESC';
		$criteria->compare('languageId', $model->id);
		$config = array(
			'criteria'=>$criteria,
		);
		$commentDataProvider = new CActiveDataProvider('Comment', $config);

		$data = array(
			'model'=>$model,
			'navList'=>Language::createList($model->page->chapterId),
			'comment'=>$comment,
			'translation'=>$translation,
			'commentDataProvider'=>$commentDataProvider,
		);
		$this->render('view', $data);
	}

	protected function _create() {
		$scenario = 'insert';
		if (Yii::app()->user->isGuest) $scenario = 'insertGuest';
		$model = new Language($scenario);
		$uploadedModels = array();
		$page = new Page('insertLanguage');
		$chapter = new Chapter('insertLanguage');

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model, $chapter, $page);

		$valid = true;
		if (isset($_POST['Chapter'])) {
			$chapter->attributes = $_POST['Chapter'];
			$valid = $chapter->validate() && $valid;
		}

		if (isset($_POST['Page'])) {
			$page->attributes = $_POST['Page'];
			$valid = $page->validate() && $valid;
		}

		if (isset($_POST['Language'])) {
			$model->attributes = $_POST['Language'];
			$images = CUploadedFile::getInstancesByName('images');
			if (!$images) {
				$model->addError('image', 'Image cannot be blank.');
			} else {
				foreach ($images as $image) {
					$language = new Language($scenario);
					$language->attributes = $_POST['Language'];
					$language->file = $image;
					$valid = $language->validate() && $valid;
					if ($valid) {
						$uploadedModels[] = $language;
					}
				}
				if ($valid) {
					$transaction = $model->dbConnection->beginTransaction();
					$saved = true;
					$sequence = $page->sequence;
					$subSequence = $page->subSequence;
					foreach ($uploadedModels as $uploadedModel) {
						// Named $page1 to avoid name conflict
						$page1 = $this->loadPage(
							$chapter->id, $sequence, $subSequence
						);
						if (!$page1) {
							$page1 = new Page('insertLanguage');
							$page1->chapterId = $chapter->id;
							$page1->sequence = $sequence;
							$page1->subSequence = $subSequence;
							$saved = $page1->save(false) && $saved;
						}
						if (!$saved) break;

						$sequence++;
						$subSequence = ''; // SubSequence only applied to first
						$uploadedModel->pageId = $page1->id;
						$uploadedModel->viewCount = 0;
						$user = Yii::app()->user;
						if (!$user->isGuest) {
							$uploadedModel->userId = $user->id;
						}
						$saved = $uploadedModel->save(false) && $saved;
						if (!$saved) break;
					}

					if ($saved) {
						$transaction->commit();
						$page->sequence = $sequence;
						$page->subSequence = '';
					} else {
						$transaction->rollBack();
						$uploadedModels = array();
					}
				}
			}
		} else {
			$model->value = 'English';
		}

		$r = array(
			'model'=>$model,
			'uploadedModels'=>$uploadedModels,
			'chapter'=>$chapter,
			'page'=>$page,
		);

		return $r;
	}

	/**
	 * Creates a new model.
	 */
	public function actionCreate() {
		// set_time_limit(600);

		$data = $this->_create();

		if ($data['chapter']->mangaId) {
			$chapterListData = $data['chapter']->listData();
		} else {
			$chapterListData = array();
		}

		$data['chapterListData'] = $chapterListData;
		$this->render('create', $data);
	}

	public function doRestCreate($data) {
		$results = $this->_create();
		
		$ids = array();
		foreach ($results['uploadedModels'] as $uploadedModel) {
			$ids[] = $uploadedModel->id;
		}
		
		$data = array(
			'success'=>true,
			'message'=>'Record(s) Created',
			'data'=>array(
				'ids'=>$ids
			)
		);
		
		$this->renderJson($data);
	}

	protected function loadPage($chapterId, $sequence, $subSequence) {
		$criteria = new CDbCriteria();
		$criteria->compare('chapterId', $chapterId);
		$criteria->compare('sequence', $sequence);
		if ($subSequence) {
			$criteria->compare('subSequence', $subSequence);
		} else {
			$criteria->addCondition("subSequence = ''");
		}
		return Page::model()->find($criteria);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' 
	 * page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);
		$page = $model->page;
		$page->scenario = 'insertLanguage';
		$chapter = $model->page->chapter;
		$chapter->scenario = 'insertLanguage';

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		$valid = true;
		if (isset($_POST['Page'])) {
			$page->attributes = $_POST['Page'];
			$valid = $page->validate() && $valid;
		}

		if (isset($_POST['Chapter'])) {
			$chapter->attributes = $_POST['Chapter'];
			$valid = $chapter->validate() && $valid;
		}

		if (isset($_POST['Language'])) {
			$model->attributes = $_POST['Language'];
			$valid = $model->validate() && $valid;
			if ($valid) {
				$transaction = $model->dbConnection->beginTransaction();
				$saved = true;
				$dbPage = $this->loadPage(
					$chapter->id, $page->sequence, $page->subSequence
				);
				if (!$dbPage) {
					$page = new Page('insertLanguage');
					$page->attributes = $_POST['Page'];
					$page->chapterId = $chapter->id;
					$saved = $page->save(false) && $saved;
				} else {
					$page = $dbPage;
				}
				if ($saved) {
					$model->pageId = $page->id;
					$user = Yii::app()->user;
					if (!$user->isGuest) $model->userId = $user->id;
					$saved = $model->save(false) && $saved;
				}
				if ($saved) {
					$transaction->commit();
//					$this->redirect(array('view', 'id'=>$model->id));
				} else {
					$transaction->rollBack();
				}
			}
		}

		if ($chapter->mangaId) {
			$chapterListData = $chapter->listData();
		} else {
			$chapterListData = array();
		}

		$data = array(
			'model'=>$model,
			'chapter'=>$chapter,
			'page'=>$page,
			'chapterListData'=>$chapterListData,
		);
		$this->render('update', $data);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin'
	 * page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we
			// should not redirect the browser
			if (!isset($_GET['ajax'])) {
				$set = isset($_POST['returnUrl']);
				$this->redirect($set ? $_POST['returnUrl'] : array('admin'));
			}
		} else {
			throw new CHttpException(
				400, 'Invalid request. Please do not repeat this request again.'
			);
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$config = array(
			'criteria'=>array(
				'order'=>'updatedAt DESC',
			),
		);
		$dataProvider = new CActiveDataProvider('Language', $config);
		$this->render('index', array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Language('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Language'])) $model->attributes = $_GET['Language'];

		$this->render('admin', array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET
	 * variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Language::model()->findByPk($id);
		if ($model === null) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model, $chapter, $page) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'language-form') {
			$json = CActiveForm::validate(array($model, $chapter, $page));
			$array = json_decode($json, true);
			if (isset($array['Language_file'])) {
				unset($array['Language_file']);
				echo json_encode($array);
			} else {
				echo $json;
			}
			Yii::app()->end();
		}
	}

	protected function performCommentAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'comment-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	protected function performTranslationAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'translation-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionAjaxUpdateCounter() {
		$id = $_POST['id'];
		$model = $this->loadModel($id);
		if ($model) {
			$model->viewCounter++;
			$model->save();
			echo 'OK';
		} else {
			echo '0';
		}
		Yii::app()->end();
	}

}
